package ru.hh.team02.chat.client;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientReader implements Runnable {
    private final static int SERVER_PORT = 2004;
    private final static int CLIENT_PORT = 5555;

    private StringSocket serverChannel;
    private StringSocket localChannel;
    
    public static void main(String[] args) {
        ClientReader reader = new ClientReader();
        reader.run();
    }
    @Override
    public void run() {
        try {
            connect();
            System.out.println("connected to localhost in port 2004");
            
            String message = "";
            do {                
                if (localChannel.available()) {
                    message = localChannel.read();
                    serverChannel.write(message);
                }
                
                if (serverChannel.available()) {
                    System.out.println(serverChannel.read());
                }
            } while (!message.equals("exit"));
        } catch (UnknownHostException unknownHost) {
            System.err.println("You are trying to connect to an unknown host!");
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } finally {
            if (serverChannel != null) serverChannel.close();
            if (localChannel != null) localChannel.close();
        }
    }
    
    private void connect() throws UnknownHostException, IOException {
        serverChannel = new StringSocket(new Socket("localhost", SERVER_PORT));
        ServerSocket serverSocket = new ServerSocket(CLIENT_PORT);
        System.out.println("waiting for input console...");
        localChannel = new StringSocket(serverSocket.accept());
        serverSocket.close();
    }
}
